﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging;

namespace StaticFilesSample.Controllers
{
    public class DefaultController : Controller
    {
        private readonly ILogger<DefaultController> _logger;
        private readonly IFileProvider _fileProvider;
        public DefaultController(IFileProvider fileProvider,
            ILogger<DefaultController> logger)
        {
            _fileProvider = fileProvider;
            _logger = logger;
        }
        public async Task<IActionResult> Index()
        {
            //throw new Exception(nameof(Index));
            _logger.BeginScope("scope:{0}", 4);
            //await GetEmbeddedAssetsContentAsync();
            await GetEmbeddedAssetsContentFromEmbeddedFileProviderAsync();
            return View(_fileProvider.GetDirectoryContents(""));
        }

        private async Task<string> GetEmbeddedAssetsContentFromEmbeddedFileProviderAsync()
        {
            var entryAssembly = Assembly.GetEntryAssembly();
            var embeddedProvider = new EmbeddedFileProvider(entryAssembly);
            var file = embeddedProvider.GetFileInfo("/OutputFiles/default.html");
            using (var sr = new StreamReader(file.CreateReadStream()))
            {
                var content = await sr.ReadToEndAsync();
                return content;
            }
        }

        private static async Task<string> GetEmbeddedAssetsContentAsync()
        {
            var entryAssembly = Assembly.GetEntryAssembly();
            var stream = entryAssembly.GetManifestResourceStream("StaticFilesSample.OutputFiles.default.html");
            using (var sr = new StreamReader(stream))
            {
                var content = await sr.ReadToEndAsync();
                return content;
            }
        }

        [Route("errorpage")]
        public IActionResult ErrorPage(int code)
        {
            return View(code);
        }
        public IActionResult Error()
        {
            return View();
        }
    }
}